require File.expand_path('../models/ProfileModel', File.dirname(__FILE__))
require 'json'
require "digest/md5"
class Users < Controller
  def add
    # telphone=13326511992&password=guavaguava00 jsonp.html:49
    # guava jsonp.html:50
    # http://127.0.1.1:4567/do/Users/add

    page=ProfileModel.find_by(telphone:@params[:telphone])
    if page==nil
      # puts "page is null"
      p=ProfileModel.new
      p.telphone=@params[:telphone]
      p.password=Digest::MD5.hexdigest(@params[:password])
      p.aboutme=""
      p.save
      self.outjsonp(p.to_json)
    else
      # puts "page is no null"
      self.outjsonp("{state:'used'}")
    end
  end


  def login
    # telphone=13326511992&password=guavaguava00 jsonp.html:49
    # guava jsonp.html:50
    # http://127.0.1.1:4567/do/Users/add
    puts "here"
    page=ProfileModel.find_by(telphone:@params[:telphone],password:Digest::MD5.hexdigest(@params[:password]))
    if page==nil
      # puts "page is null"
      have=ProfileModel.find_by(telphone:@params[:telphone])
      if have
        self.outjsonp("{state:'password error'}")
      else
        self.outjsonp("{state:'no this user'}")
      end

    else
      # puts "page is no null"
      @session[:telphone]=page.telphone
      # self.outjsonp(page.to_json)
      self.outjsonp(@session[:telphone])
    end
  end

  def getstate
    if @session[:telphone]==nil
      self.outjsonp("{state:'did not login'}")
    else
      self.outjsonp(@session[:telphone])
    end
  end

  def logout
    @session[:telphone]=nil
    self.outjsonp("{state:'logout finished'}")
  end

  def aboutme
    profile=ProfileModel.find_by(id:@params[:id])

    if profile!=nil
      profile.aboutme=@params[:aboutme]
      profile.save
      self.outjsonp("{state:'saved aboutme'}")
    else
      self.outjsonp("{state:'no this id")
    end

  end
end